package com.ruoyi.delivery.service.impl;

import com.ruoyi.delivery.domain.DelDeliveryDetail;
import com.ruoyi.delivery.domain.DelDeliveryOrderBatch;
import com.ruoyi.delivery.domain.DelTransportDetail;
import com.ruoyi.delivery.domain.DelTransportOrder;
import com.ruoyi.delivery.mapper.*;
import com.ruoyi.delivery.service.IDelTransportOrderService;
import com.ruoyi.delivery.utils.IdUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DelTransportOrderServiceImpl implements IDelTransportOrderService {


    private final DelTransportOrderMapper transportOrderMapper;
    private final DelTransportDetailMapper transportDetailMapper;
    private final DelDeliveryOrderMapper deliveryOrderMapper;
    private final DelDeliveryDetailMapper deliveryDetailMapper;
    private final DelVehicleMapper vehicleMapper;
    private final DelAllocationOrderMapper allocationOrderMapper;

    public DelTransportOrderServiceImpl(DelTransportOrderMapper transportOrderMapper, DelTransportDetailMapper transportDetailMapper, DelDeliveryOrderMapper deliveryOrderMapper, DelDeliveryDetailMapper deliveryDetailMapper, DelVehicleMapper vehicleMapper, DelAllocationOrderMapper allocationOrderMapper) {
        this.transportOrderMapper = transportOrderMapper;
        this.transportDetailMapper = transportDetailMapper;
        this.deliveryOrderMapper = deliveryOrderMapper;
        this.deliveryDetailMapper = deliveryDetailMapper;
        this.vehicleMapper = vehicleMapper;
        this.allocationOrderMapper = allocationOrderMapper;
    }

    @Override
    public List<DelTransportOrder> filterTransportOrders(
            String logisticId,
            String trackingNumber,
            String origin,
            String destination,
            String startDate,
            String endDate,
            String state,
            String customerType,
            int page,
            int pageSize
    ) {
        // 计算分页的起始偏移量
        int offset = (page - 1) * pageSize;
        return transportOrderMapper.filterTransportOrders(
                logisticId,
                trackingNumber,
                origin,
                destination,
                startDate,
                endDate,
                state,
                customerType,
                offset,
                pageSize
        );
    }

    @Override
    public int getTransportOrderCount(
            String logisticId,
            String trackingNumber,
            String origin,
            String destination,
            String startDate,
            String endDate,
            String state,
            String customerType
    ) {
        return transportOrderMapper.getTransportOrderCount(
                logisticId,
                trackingNumber,
                origin,
                destination,
                startDate,
                endDate,
                state,
                customerType
        );
    }

    @Override
    public boolean insertTransportOrder(DelTransportOrder order) {
        return transportOrderMapper.insertTransportOrder(order) > 0;
    }

    @Override
    public boolean deleteTransportOrder(String trackingNumber) {
        return transportOrderMapper.deleteTransportOrder(trackingNumber) > 0;
    }

    @Override
    public boolean updateTransportOrder(DelTransportOrder order) {
        return transportOrderMapper.updateTransportOrder(order) > 0;
    }

    @Override
    public List<DelTransportDetail> getDetailsByTrackingNumber(String trackingNumber) {
        return transportDetailMapper.getDetailsByTrackingNumber(trackingNumber);
    }

    // 更新时间为当前时间
    @Override
    public int confirmTransportOrder(String trackingNumber, String updatedPerson) {
        return transportOrderMapper.updateTransportOrderState(trackingNumber, "待配送", updatedPerson);
    }

    @Transactional
    @Override
    public List<DelDeliveryOrderBatch> generateDeliveryOrder(String logisticDeliver, List<String> exclusionVehicle, List<String> trackingNumberList) {
        var vehicles = vehicleMapper.getAllVehicle(logisticDeliver);
        vehicles.removeIf(vehicle -> exclusionVehicle.contains(vehicle.getVehicleNo()));
        if (vehicles.isEmpty()) {
            return List.of();
        }

        var transportOrders = new ArrayList<DelTransportOrder>();
        for (var trackingNumber : trackingNumberList) {
            var order = transportOrderMapper.getTransportOrderByTrackingNumber(trackingNumber);
            if (order == null) {
                continue;
            }
            if (order.getState() != "待配送") {
                return List.of();
            }
            transportOrders.add(order);
        }

        // 生成配送单（随机）
        // 打乱车辆顺序
        var randomVehicles = new ArrayList<String>();
        //Math.random() * (max - min + 1) + min
        while (!vehicles.isEmpty()) {
            var randomIndex = (int) (Math.random() * vehicles.size());
            randomVehicles.add(vehicles.get(randomIndex).getVehicleNo());
            vehicles.remove(randomIndex);
        }
        var tmpOrders = new ArrayList<DelDeliveryOrderBatch>();
        var generatedOrders = new ArrayList<DelDeliveryOrderBatch>();
        var deliveryId = "D13002";
        var i = "1";

        for (var vehicle : randomVehicles) {
            var order = new DelDeliveryOrderBatch();
            order.setDeliveryType("未知");
            order.setDeliveryId(deliveryId);
            order.setDeliveryBatchId(deliveryId + "-" + i);
            if (i.equals("1")) {
                i = "2";
            }else if(i.equals("2")) {
                i = "3";
            }else{
                i = "4";
            }
            order.setOrigin("Unknown");
            order.setState("待发货");
            order.setWeight(0.0);
            order.setWeightUnit("Unknown");
            order.setLogisticId(logisticDeliver);
            order.setVehicleNumber(vehicle);
            order.setGeneratedDate(Date.from(Instant.now()));
            order.setUpdatedDate(Date.from(Instant.now()));
            order.setUpdatedPerson("1009898");
            tmpOrders.add(order);
        }

        var generatedDetails = new ArrayList<DelDeliveryDetail>();
        //滚动车辆直到所有运输订单明细都被分配

        //按目的地分组
        var destinationGroup = transportOrders.stream().collect(Collectors.groupingBy(DelTransportOrder::getRoute));
        //假设一辆车负载无上限
        var currentVehicleIndex = 0;
        for (var it : destinationGroup.entrySet()) {
            var route = it.getKey();
            var transportOrderList = it.getValue();

            for (var order : transportOrderList) {
                if (currentVehicleIndex >= randomVehicles.size()) {
                    return List.of();
                }
                var aimedDeliveryOrder = tmpOrders.get(currentVehicleIndex);

                var detailList = transportDetailMapper.getDetailsByTrackingNumber(order.getTrackingNumber());

                aimedDeliveryOrder.setOrigin(order.getOrigin());

                //强制更新（不进行单位换算）
                aimedDeliveryOrder.setWeightUnit(order.getWeightUnit());
                aimedDeliveryOrder.setWeight(aimedDeliveryOrder.getWeight() + order.getWeight());

                for (var detail : detailList) {
                    var deliveryDetail = new DelDeliveryDetail();
                    deliveryDetail.setDeliveryDetailId("DD" + IdUtils.myId());
                    deliveryDetail.setTransportDetailId(detail.getTransportDetailId());
                    deliveryDetail.setTrackingNo(order.getTrackingNumber());
                    deliveryDetail.setDestination(route.getValue());
                    deliveryDetail.setDeliveryBatchId(deliveryId + "-1");
                    deliveryDetail.setState("待发货");
                    deliveryDetail.setWeight(detail.getWeight());
                    deliveryDetail.setWeightUnit(detail.getWeightUnit());
                    deliveryDetail.setTransportQuantity(detail.getTransportQuantity());

                    deliveryDetail.setType(detail.getType());
                    deliveryDetail.setOrderId(detail.getOrderNumber());
                    deliveryDetail.setProductBatch(detail.getProductBatch());
                    deliveryDetail.setProductName(detail.getProductName());
                    deliveryDetail.setGeneratedDate(order.getGeneratedDate());
                    deliveryDetail.setUpdatedDate(Date.from(Instant.now()));
                    deliveryDetail.setUpdatedPerson("1009898");
                    deliveryDetail.setWarehouseId(allocationOrderMapper.getWarehouseNoByOrderNo(detail.getOrderNumber()));
                    //7天后的时间
                    deliveryDetail.setExpectedDeliveryTime(Date.from(Instant.now().plusSeconds(7 * 24 * 60 * 60)));
                    generatedDetails.add(deliveryDetail);
                }

                if (!generatedOrders.contains(aimedDeliveryOrder)) {
                    generatedOrders.add(aimedDeliveryOrder);
                }

            }
            currentVehicleIndex++;

        }


        //插入配送单
        for (var order : generatedOrders) {
            deliveryOrderMapper.insertDeliveryOrder(order);
        }
        //插入配送明细
        for (var detail : generatedDetails) {
            deliveryDetailMapper.insertDeliveryDetail(detail);
        }

        transportOrders.forEach(order -> transportOrderMapper.updateTransportOrderState(order.getTrackingNumber(), "运输中", "1009898"));

        return generatedOrders;
    }

    /**
     * 修改预期到货时间
     *
     * @param trackingNumber 运单号
     * @param departureDate  新的到货时间
     * @param updatedPerson  修改人
     */
    public void changeExpectedArrivalTime(String trackingNumber, String departureDate, String updatedPerson) {
        transportOrderMapper.updateExpectedArrivalTime(trackingNumber, departureDate, updatedPerson);
    }
}
